package com.esyoga.yoyoga.handler;

import com.esyoga.yoyoga.util.WebSocketUtil;
import org.springframework.stereotype.Controller;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
@Controller
@ServerEndpoint("/ChatHandler/{uname}")
public class ChatHandler  {

    @OnOpen       //建立起连接的时候调用的方法
    public void openSession(@PathParam("uname") String uname, Session session){

        //System.out.println("+++++++++++++++++++++");
        //System.out.println("=============================="+springServletContextUtil.getApplicationContext());
        String message="欢迎:"+uname+"加入群聊";
        //将当前用户放入群里面
        WebSocketUtil.SESSIONMAP.put(uname, session);
        //向所有人发送消息
        WebSocketUtil.sendAll(message);
    }
    //接收到消息
    @OnMessage
    public void onMessage(@PathParam("uname")String uname, String message){
        if(message.split("\\|").length>1){
           // System.out.println(uname);
           // System.out.println(message);
            String [] messageanduser=message.split("\\|");
            String sendmessages=messageanduser[0];
            String user=messageanduser[1];
            String sendmes=uname+":"+sendmessages;
        /*System.out.println(sendmessages);
        System.out.println(user);
        System.out.println(WebSocketUtil.SESSIONMAP.get(user));*/
            if(WebSocketUtil.SESSIONMAP.get(user)!=null){
                //System.out.println("进了if");
                WebSocketUtil.sendMessage(WebSocketUtil.SESSIONMAP.get(user),sendmes);
            }
        }
        else{
           // System.out.println("进了其他");
            message=uname+":"+message;
            WebSocketUtil.sendAll(message);
        }

    }
    @OnClose//离开聊天室
    public void onClose(@PathParam("uname")String uname,Session session){

        //将当前用户注销
        WebSocketUtil.SESSIONMAP.remove(uname);
        //群发消息
        WebSocketUtil.sendAll("用户:"+uname+"离开聊天室");
        //关闭session
        try {
            session.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
    //连接时出异常
    public void onError(Session session,Throwable throwable){
        try {
            session.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
